package cn.chen.controller;

import cn.chen.model.Notice;
import cn.chen.service.NoticeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbpu
 * @since 2023-05-28
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;
    //添加公告
    @PostMapping("/add")
    public boolean addNotice(@RequestBody Notice notice){
        //填充公告发布时间
        notice.setPublicTime(String.valueOf(LocalDateTime.now()));
        return noticeService.save(notice);
    }

    //分页查询公告列表
    @GetMapping("/list")
    public List<Notice> list(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size,
                             @RequestParam(required = false) String title){
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Notice::getPublicTime);
        if (title != null){
            wrapper.like(Notice::getTitle, title);
            Page<Notice> noticePage = noticeService.page(new Page<>(1, 20), wrapper);
            return noticePage.getRecords();
        }
        Page<Notice> noticePage = noticeService.page(new Page<>(page, size), wrapper);
        return noticePage.getRecords();

    }

    //根据id查询公告
    @GetMapping("/getNoticeById")
    public Notice getNoticeById(@RequestParam Integer id){
        return noticeService.getById(id);
    }

}
